package oracle;

import format.Format;

public class TraitFormatOracle {
	/**
	 * 
	 * Convert a Format with decimal value(s) and 
	 * return the hexadecimal value(s) (String). 
	 * It can receive the format 0, 1, 2, and 3
	 * if an error occurs, null is returned
	 * 
	 * @param f : Float format to convert
	 * @return Format converted to hexadecimal
	 */
	public static String oracle(Format f) {
		
		int type = f.getNoFormat(),  nb = 0;
		String valHex = "";
		if (type == 1) { nb = 1; }
		if (type == 2 || type == 3) { nb = 2; }
		if (type == 0) { nb = 0; valHex += f.getValEntree(); }
		
		//Conversion of each float number
		for (int j = 0; j < nb; ++j) {
			//Adding Space for format 3 (HH HH)
			if (j != 0 && type == 3) { valHex += " ";}
			//Conversion via method decToHex
			valHex += decToHex(f.getOctetB10(j));
		}
		
		return valHex;
	}
	/**
	 * 
	 * Convert a decimal under 255 to its hexadecimal form
	 * if an error occurs, null is returned
	 * 
	 * @param valDec : decimal int to convert
	 * @return Hexadecimal value of valDec
	 */
	private static String decToHex(int valDec) {
		//decimal which is too big
		if (valDec > 255) return null;
		
		String valHex = "";
		int partInt  = 0, reste = 0;
		
		partInt = valDec / 16;
		reste   = valDec%16;
		
		if (partInt > 16) { valHex = null; }
		//Zero As first character 
		//if the number is under 17
		else if (partInt < 10) { valHex += partInt; }
		else if (partInt > 9)  { valHex += (char)(55 + partInt); }
		
		if (reste > 16) { valHex = null; }
		else if (reste < 10)
			valHex += reste;
		else {
			valHex += (char)('A' + reste - 10);
		}
		return valHex;
	}
}
